package com.example.music_admin.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * <p>
 * 文件处理控制器
 * </p>
 *
 * @author jerry
 * @since 2025-03-17
 */
@RestController
@RequestMapping("/file")
public class FileController {

    //json的解析工具
    ObjectMapper jsonTool = new ObjectMapper();

    //提供一个文件上传的接口【头像-图片】
    @RequestMapping(value = "/avatar/upload", method = RequestMethod.POST)
    public String uploadImage(@RequestParam("file") MultipartFile file) throws JsonProcessingException {
        //文件上传的路径
        String path = "E:\\music-server\\avatorImages\\";
        //文件上传
        String result = upload(file, path);
        //返回文件路径
        return result;
    }

    //提供一个文件上传的接口【音乐-文件】
    @RequestMapping(value = "/music/upload", method = RequestMethod.POST)
    public String uploadMusic(@RequestParam("file") MultipartFile file) throws JsonProcessingException {
        //文件上传的路径
        String path = "E:\\music-server\\song\\";
        //文件上传
        String result = upload(file, path);
        //返回文件路径
        return result;
    }

    //文件上传的方法
    public String upload(MultipartFile file, String path) throws JsonProcessingException {
        //请求结果map的定义
        HashMap result = new HashMap();
        //文件非空校验
        if (file.isEmpty()) {
            result.put("success", false);
            result.put("message", "上传文件为空");
            return jsonTool.writeValueAsString(result);
        }
        //获取文件名【生成唯一的文件名】 【1、uuid获取文件名 2、获取文件的后缀】
        String fileName = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
        //构建文件对象
        File dest = new File(path + fileName);
        //写出文件【上传文件到本地硬盘】
        try {
            //1、写出文件到硬盘
            file.transferTo(dest);
            result.put("success", true);//表示成功
            //2、文件上传路径的判断
            if (path.contains("avatorImages")) {
                result.put("path", "/music/avatorImages/" + fileName);
            } else if (path.contains("/song")) {
                result.put("path", "/music/song/" + fileName);
            } else if (path.contains("/img/")) {
                result.put("path", "/music/img/songPic/" + fileName);
            } else {
                result.put("path", "/music/upload/" + fileName);
            }

        } catch (IOException e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "上传文件失败，请稍后重试");
        }
        //返回文件路径
        return jsonTool.writeValueAsString(result);
    }

}

